package cn.itcast.realm;

import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class SaasRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    protected ModuleService moduleService;

    @Override // 认证方法
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String email = token.getUsername(); //从token中获取邮箱
        String password_page = new String(token.getPassword()) ; //从token中获取密码
        User user = userService.findByEmail(email);
        if (user!=null){
            String password_db = user.getPassword();
            if(password_db.equals(password_page)){
//                Object principal, Object credentials 已加密后的密码, String realmName 当前realm的名称
                return new SimpleAuthenticationInfo(user,password_page,getName());
            }
        }

        return null; // 如果这里直接return null 那么subject认证方法就会抛异常
    }


    @Override  // 授权方法
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        判断当前登录人有哪些权限  告诉shiro框架当前登录人有哪些权限
        System.out.println("***************************************************************");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        告诉shiro有哪些权限
//        User user = (User) SecurityUtils.getSubject().getPrincipal();
        User user = (User) principalCollection.getPrimaryPrincipal();
        List<Module> moduleList = moduleService.findModuleListBy(user);
        for (Module module : moduleList) {
            info.addStringPermission(module.getName());
        }
        return info;
    }


}
